#!/bin/env python
#-*- coding:utf-8 -*-

#----------------------------------------------------------------------------
# Name     :      start.py
# Purpose  :      gui starter, include app module and splash code.
# Author   :      Albert cheng
# Created  :      2012-10-29
# Copyright:     (c) 2012 by Albertcheng
# Licence  :      wxWindows license
#----------------------------------------------------------------------------
import sys
import os
import wx
from log import Log
from gui import GUITool

from note_gui import new_notebook
from request_handler import request_mysql,request_sqlite
from gui_dbconfig import DBConfigDialog
import wx.lib.mixins.inspection


class MyApp(wx.App, wx.lib.mixins.inspection.InspectionMixin):
    def OnInit(self):

        self.InitInspection()  # for the InspectionMixin base class
        wx.SystemOptions.SetOptionInt("mac.window-plain-transition", 1)
        self.SetAppName("myguitool")
        
        splash = MySplashScreen()
        splash.Show()

        return True


class MySplashScreen(wx.SplashScreen):
    def __init__(self):
        
        def opj(path):
            """Convert paths to the platform-specific separator"""
            st = apply(os.path.join, tuple(path.split('/')))
            # HACK: on Linux, a leading / gets lost...
            if path.startswith('/'):
                st = '/' + st
            return st

        self.Log = Log()
        self.Log.log("start splash screen.")
        bmp = wx.Image(opj("bitmaps/startup.png")).ConvertToBitmap()
        wx.SplashScreen.__init__(self, bmp,
                                 wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT,
                                 900, None, -1)
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        self.fc = wx.FutureCall(500, self.Test_conn)#Test)
        #self.fc = wx.FutureCall(500, self.Test)

    def OnClose(self, evt):
        evt.Skip()
        self.Hide()
        self.Log.log("close splash screen.")

    def ShowMain(self,Type = "config"):
        
        self.Log.log("start main GUI window.")
        frame = new_notebook(None, -1, self.Log,"GM Tool For Ion Hammer", Type)
        frame.Show()
        frame.Center()
        if self.fc.IsRunning():
            self.Raise()
            
    def Test_conn(self):
        b = request_sqlite(self.Log)
        cfg = b.get()
        db_cfg = cfg[0]
        
        
        busy = wx.BusyInfo("Now connecting to mysql server, Wait for a monment..")
        wx.Yield()
        a = request_mysql(self.Log,db_cfg)
        e = a.do_test(db_cfg)
        
        if e != 0:
            errormsg = e[1]
            errormsg = errormsg+"\n点击【确认】前往修改mysql配置数据，点击cancel关闭工具".decode("utf-8")
            error_dlg = wx.MessageDialog(self, errormsg,
                               'Mysql Connect Error',
                               wx.OK | wx.ICON_INFORMATION | wx.CANCEL
                               )
            rd = error_dlg.ShowModal()
            error_dlg.Destroy()
            
            if rd == wx.OK or rd == 5100:
                self.ShowMain(Type = "config")
            elif rd == wx.CANCEL or rd == 5101:
                sys.exit(1)
            else:
                wx.MessageBox("未知问题，请联系程洁！".decode('utf-8'),"Unknow Error",wx.OK)
                sys.exit(1)
        else:
            self.Log.log("Mysql connected successful. ready to run background thread.") 
            self.ShowMain(Type = "normal")
        del busy
        
def main():
    try:
        toolpath = os.path.dirname(__file__)
        os.chdir(toolpath)
    except:
        pass
    app = MyApp(False)
    app.MainLoop()
    
Title_Msg = "Mysql Operation Tool for Ion Hammer Development Team: (Presented by albertcheng)"       
if __name__ == '__main__':
    main()


